package io.netty.example.mytest.nio.reactor;

import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

/**
 * @ClassName ReadEventHandler
 * @Description read事件句柄
 * @Author dukezeng
 * @CreatedTime 2019/4/13 18:08
 * @Version 1.0
 **/
public class ReadEventHandler implements EventHandler {
    private Selector demultiplexer;
    private ByteBuffer inputBuffer = ByteBuffer.allocate(2048);

    public ReadEventHandler(Selector demultiplexer) {
        this.demultiplexer = demultiplexer;
    }

    public void handleEvent(SelectionKey handle) throws Exception {
        System.out.println("===== Read Event Handler =====");

        SocketChannel socketChannel = (SocketChannel) handle.channel();
        socketChannel.read(inputBuffer);
        inputBuffer.flip();

        byte[] buffer = new byte[inputBuffer.limit()];
        inputBuffer.get(buffer);
        System.out.println("Received message from client : " + new String(buffer));

        socketChannel.register(demultiplexer, SelectionKey.OP_WRITE, buffer);
    }
}
